package edu.gatech.cs4235.group3.action;

import java.io.BufferedInputStream;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

import edu.gatech.cs4235.group3.domain.Message;
import edu.gatech.cs4235.group3.exception.OneTimePadException;

public class SetupAction extends OnePadEncryptAction {
	
	private String fileName = null;

	public SetupAction(final String fileName) {
		super(fileName, "oneTimePad.txt");
		
		this.fileName = fileName;
		// TODO Auto-generated constructor stub
	}

	@Override
	public void performAction() throws OneTimePadException {
		
		Message pad = new Message("oneTimePad.txt");
		
		File file = new File(fileName);
		
		FileInputStream fileInputStream = null;
		BufferedInputStream bufferedInputStream = null;
		DataInputStream data = null;
		
		try {
			fileInputStream = new FileInputStream(file);
			
			bufferedInputStream = new BufferedInputStream(fileInputStream);
			
			data = new DataInputStream(bufferedInputStream);
			
			char[][] padText = pad.getText();
			
			int count = 0;
			
			while (data.available() > 0) {
				
				Message message = new Message();
				Message plainText = new Message();
				
				char[][] text = message.getText();
				char[][] plaintxt = plainText.getText();
				
				boolean exit = false;
				
				// encrypts the data.
				for (int i = 0; i < text.length; i++) {
					
					for (int j = 0; j < text[i].length; j++) {
						
						// Read a valid byte.
						char byteRead = 0;
						while (data.available() > 0) {
							byteRead = (char) data.readByte();
							if (byteRead >= 32 && byteRead <= 126) {
								break;
							}
						}
						
						if (data.available() == 0) {
							exit = true;
							break;
						}
						
						
						plaintxt[i][j] = byteRead;
						text[i][j] = this.crypt(byteRead, padText[i][j]);
					}
					
					if (exit) {break;}
				}
				
				if (!exit) {
					plainText.saveMessage("plain/" + count + fileName);
					message.saveMessage("encrypt/" + count + fileName);
				}
				
				count++;
			}
			
			fileInputStream.close();
			bufferedInputStream.close();
			data.close();
			
			
		} catch (final IOException ioe) {
			
		}


	}

}
